package han.fetch;

import com.han.http.client.exception.RequestNotExecutedException;
import com.han.http.client.method.BaseHttpRequest;
import com.han.http.client.method.HttpGet;
import com.han.http.client.paramter.RequestHeader;

import java.io.IOException;
import java.net.Proxy;

/**
 * @fileName: Fetcher
 * @author: Han
 * @date: 2018/6/25 17:36
 * @dscription: 抓取url内容的方法集成
 */
public class Fetcher {

    /**
     * 使用指定参数获取指定url的内容
     *
     * @param urlStr         url
     * @param requestHeaders 请求头
     * @param connectTimeout 连接超时时间
     * @param readTimeout    读取超时时间
     * @param proxy          代理
     * @return 目标内容
     * @throws RequestNotExecutedException 异常
     * @throws IOException                 抛出各种异常
     */
    public String getInfoByGet(String urlStr, RequestHeader[] requestHeaders, int connectTimeout,
                               int readTimeout, Proxy proxy) throws IOException, RequestNotExecutedException {
        String info;

        HttpGet httpGet = BaseHttpRequest.getGetMethod(urlStr);
        httpGet.setConnectTimeout(1000 * connectTimeout);
        httpGet.setReadTimeout(1000 * readTimeout);
        httpGet.setHeaders(requestHeaders);
        httpGet.setProxy(proxy);
        try {
            httpGet.execute();
            info = httpGet.getText();
        } finally {
            try {
                httpGet.disconnect();
            } catch (RequestNotExecutedException e) {
                e.printStackTrace();
            }
        }

        return info;
    }
}
